﻿using System.Text.RegularExpressions;
using System.Xml.Linq;
using PengSW.NotifyPropertyChanged;
using PengSW.XmlHelper;
using static PengSW.XmlHelper.XmlLinqHelper;
using static PengSW.RuntimeLog.RL;
using System;

namespace PengSW.XmlImport
{
    public class ReplacePattern : NotifyPropertyChangedObject, IXmlSeriable
    {
        public ReplacePattern(ReplaceRule aReplaceRule)
        {
            ReplaceRule = aReplaceRule;
        }

        public ReplaceRule ReplaceRule { get; }

        public string Pattern { get { return _Pattern; } set { SetValue(ref _Pattern, value, nameof(Pattern)); _Regex = null; } }
        private string _Pattern;

        public string To { get { return _To; } set { SetValue(ref _To, value, nameof(To)); } }
        private string _To;

        private Regex _Regex = null;
        private void CreateRegex()
        {
            try
            {
                _Regex = new Regex(Pattern);
            }
            catch (Exception ex)
            {
                _Regex = null;
                E(ex, $"CreateRegex(\"{Pattern}\", \"{To}\")");
            }
        }

        public void ReadFromXml(XElement aXElement)
        {
            if (aXElement == null) return;
            Pattern = aXElement.GetAttributeValue(nameof(Pattern), null);
            To = aXElement.GetAttributeValue(nameof(To), null);
        }

        public XElement CreateXElement(string aXmlNodeName) => new XElement(aXmlNodeName, CreateXAttribute(nameof(Pattern), Pattern), CreateXAttribute(nameof(To), To));

        public string Replace(string aValue)
        {
            if (!string.IsNullOrWhiteSpace(Pattern) && _Regex == null) CreateRegex();
            if (_Regex == null) return aValue;
            try
            {
                return _Regex.Replace(aValue, To);
            }
            catch (Exception ex)
            {
                E(ex, $"Replace(\"{aValue}\", \"{Pattern}\", \"{To}\")");
                return aValue;
            }
        }
    }
}
